<?php

namespace app\controllers;

use Yii;
use app\models\User;
use app\models\LoginForm;
use app\models\SentVerifyForm;
use app\models\RetrievePasswordForm;
use app\models\ChangePasswordForm;
use app\components\Controller;
use app\models\search\UserSearch;
use yii\web\NotFoundHttpException;
use yii\web\ConflictHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * UserController implements the CRUD actions for User model.
 */
class UserController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create','index','update','delete','changestatus'],
                'rules' => [
                    [
                        'actions' => ['create','index','update','delete','changestatus'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
            ],
        ],
 
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'maxLength'=>4,
                'minLength'=>4,
                'testLimit'=>1,

            ],
        ];
    }
    public function actionChangestatus($id)
    {
        $model = $this->findModel($id);
        $model->status == 1 ? $model->status = 0 : $model->status = 1;
        $model->repeatpassword = $model->password;
        if($model->save())
        {
            return $this->redirect(['index']);
        }
    }
    /**
     * Lists all User models.
     * @return mixed
     */
    public function actionIndex()
    {
        if(!(yii::$app->user->identity->checkAccess(User::ROLE_ADMIN) || yii::$app->user->identity->checkAccess(User::ROLE_TEACHER)))
        {
            throw new ConflictHttpException('Permission denied!');
        }
        $searchModel = new UserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionProfile($name)
    {
        return $this->render('profile', [
            'model' => User::findByUsername($name),
        ]);
    }

    /**
     * Displays a single User model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionSignup()
    {
         $model = new User();

        if ($model->load(Yii::$app->request->post())) {
            $password = $model->password;
            $model->setPassword($model->password);
            $model->repeatpassword = $model->password;
            if($model->save())
            {
                $loginForm = new LoginForm;
                $loginForm->setScenario('intelnallogin');
                $loginForm->username = $model->user_name;
                $loginForm->password = $password;
                $loginForm->login();
                return $this->redirect(['profile', 'name' => $model->user_name]);
            }
            $model->password = "";
            $model->repeatpassword = "";
            return $this->render('signup', [
                'model' => $model,
            ]);
        } else {
            return $this->render('signup', [
                'model' => $model,
            ]);
        }

    }

    /**
     * Creates a new User model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        if(!yii::$app->user->identity->checkAccess(User::ROLE_ADMIN))
        {
            throw new ConflictHttpException('Permission denied!');
        }
        $model = new User();

        if ($model->load(Yii::$app->request->post())) {
            $model->setPassword($model->password);
            if($model->save())
            {
                return $this->redirect(['profile', 'name' => $model->user_name]);
            }
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * @TODO  : 修改密码
     * @param : string $username
     * @return: boolean
     * @author: Ray
     * @date  : 2014-09-26
     */
    public function actionChangepassword()
    {
        $model = new ChangePasswordForm;
        $model->user_name = yii::$app->user->identity->user_name;
        if ($model->load(Yii::$app->request->post()) && $model->updatePassword()) {
            return $this->redirect(['profile', 'name' => $model->user_name]);
        } else {
            return $this->render('changepassword', [
                'model' => $model,
            ]);
        }
    }

    /**
     * @TODO  : 取回密码
     * @param : string $username
     * @return: boolean
     * @author: Ray
     * @date  : 2014-09-26
     */
    public function actionRetrievepassword()
    {
        $model = new SentVerifyForm;
        $modelRP = new RetrievePasswordForm;
        if(isset($_POST['RetrievePasswordForm']))
        {
            $modelRP->load(Yii::$app->request->post());
            $session = Yii::$app->session;
            $session->open();
            $user = User::findByUsername($session['username']);
            $user->setPassword($modelRP->password);
            $user->repeatpassword = $user->password;
            if($user->update())
            {
                return $this->redirect(array('site/login'));
            }
            else
            {
                throw new ConflictHttpException('Change Password Error.');
            }
        }
        if(isset($_POST['SentVerifyForm']))
        {
            $model->load(Yii::$app->request->post());
            $userModel = User::findByUsername($model->username);
            $session = Yii::$app->session;
            $session->open();
            if($session['verifyCode_'.$userModel->user_name] == $model->verifyCode)
            {
               $session['username'] = $userModel->user_name;
               return $this->render('retrievePassword',array(
                   'username'=>$userModel->user_name,
                   'model'=>$modelRP,
                ));
            }
            else
            {
                return $this->render('sendVerify',['model'=>$model,'error'=>'VerifyCode Error.']);
            }
        }
        return $this->render('sendVerify',['model'=>$model]);
    }

    /**
     * Updates an existing User model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if(!(yii::$app->user->identity->checkAccess(User::ROLE_ADMIN) || $model->user_id == yii::$app->user->identity->user_id))
        {
            throw new ConflictHttpException('Permission denied!');
        }

        if ($model->load(Yii::$app->request->post())) {
            $model->repeatpassword = $model->password;
            if($model->save())
            {
                return $this->redirect(['profile', 'name' => $model->user_name]);
            }
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing User model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if(!yii::$app->user->identity->checkAccess(User::ROLE_ADMIN))
        {
            throw new ConflictHttpException('Permission denied!');
        }
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the User model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return User the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = User::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
